package com.lihaozhe.productservice.controller;

import com.lihaozhe.productservice.dto.ProductDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 商品服务控制器
 * 提供商品管理的REST API
 *
 * @author 李昊哲
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/products")
public class ProductController {
  // 模拟商品数据
  private final List<ProductDTO> products = new ArrayList<>();
  private final Logger logger = LoggerFactory.getLogger(this.getClass());
  // 注入当前服务端口，用于标识实例
  @Value("${server.port}")
  private String serverPort;

  // 实例标识
  private final String instanceId;

  /**
   * 构造函数，初始化模拟数据
   */
  public ProductController() {
    // 初始化测试商品
    products.add(new ProductDTO(1L, "iPhone 15", "手机", 5999.00, 100, "最新款iPhone"));
    products.add(new ProductDTO(2L, "MacBook Pro", "电脑", 12999.00, 50, "专业级笔记本电脑"));
    products.add(new ProductDTO(3L, "AirPods Pro", "耳机", 1899.00, 200, "无线降噪耳机"));
    products.add(new ProductDTO(4L, "iPad Air", "平板", 4399.00, 80, "轻薄便携平板"));

    // 生成实例ID（基于时间戳）
    this.instanceId = "product-service-" + System.currentTimeMillis() % 1000;
  }

  /**
   * 根据ID获取商品  - 增强版本，返回实例信息
   * GET /api/products/{id}
   */
  @GetMapping("/{id}")
  public Map<String, Object> getProduct(@PathVariable("id") Long id) {
    logger.info("实例 {} (端口:{}) 处理商品查询请求: {}", instanceId, serverPort, id);

    simulateProcessingTime();
    Optional<ProductDTO> productOpt = products.stream()
        .filter(p -> p.getId().equals(id))
        .findFirst();

    if (productOpt.isPresent()) {
      ProductDTO product = productOpt.get();
      return Map.of(
          "product", product,
          "instanceInfo", Map.of(
              "instanceId", instanceId,
              "serverPort", serverPort,
              "timestamp", System.currentTimeMillis()
          )
      );
    }

    return Map.of(
        "product", null,
        "instanceInfo", Map.of(
            "instanceId", instanceId,
            "serverPort", serverPort,
            "timestamp", System.currentTimeMillis()
        )
    );
  }

  /**
   * 获取所有商品 - 增强版本
   * GET /api/products
   */
  @GetMapping
  public Map<String, Object> getAllProducts() {
    logger.info("实例 {} (端口:{}) 处理获取所有商品请求", instanceId, serverPort);
    simulateProcessingTime();
    return Map.of(
        "products", products,
        "instanceInfo", Map.of(
            "instanceId", instanceId,
            "serverPort", serverPort,
            "totalProducts", products.size(),
            "timestamp", System.currentTimeMillis()
        )
    );
  }

  /**
   * 根据分类获取商品
   * GET /api/products/category/{category}
   */
  @GetMapping("/category/{category}")
  public Map<String, Object> getProductsByCategory(@PathVariable("category") String category) {
    logger.info("实例 {} (端口:{}) 处理分类查询: {}", instanceId, serverPort, category);

    simulateProcessingTime();

    List<ProductDTO> categoryProducts = products.stream()
        .filter(p -> p.getCategory().equalsIgnoreCase(category))
        .toList();

    return Map.of(
        "products", categoryProducts,
        "instanceInfo", Map.of(
            "instanceId", instanceId,
            "serverPort", serverPort,
            "category", category,
            "count", categoryProducts.size(),
            "timestamp", System.currentTimeMillis()
        )
    );
  }

  /**
   * 更新商品库存
   * PUT /api/products/{id}/stock
   */
  @PutMapping("/{id}/stock")
  public Map<String, Object> updateStock(@PathVariable("id") Long id, @RequestBody Map<String, Integer> request) {
    Integer quantity = request.get("quantity");
    logger.info("实例 {} (端口:{}) 更新商品库存: {}, 数量: {}", instanceId, serverPort, id, quantity);

    // 查找商品并更新库存
    Optional<ProductDTO> productOpt = products.stream()
        .filter(p -> p.getId().equals(id))
        .findFirst();

    if (productOpt.isPresent()) {
      ProductDTO product = productOpt.get();
      int newStock = product.getStock() + quantity;
      product.setStock(Math.max(newStock, 0)); // 库存不能为负数

      return Map.of(
          "success", true,
          "message", "库存更新成功",
          "newStock", product.getStock(),
          "instanceInfo", Map.of(
              "instanceId", instanceId,
              "serverPort", serverPort,
              "timestamp", System.currentTimeMillis()
          )
      );
    }

    return Map.of(
        "success", false,
        "message", "商品不存在",
        "instanceInfo", Map.of(
            "instanceId", instanceId,
            "serverPort", serverPort,
            "timestamp", System.currentTimeMillis()
        )
    );
  }

  /**
   * 获取实例信息
   * GET /api/products/instance-info
   */
  @GetMapping("/instance-info")
  public Map<String, Object> getInstanceInfo() {
    return Map.of(
        "instanceId", instanceId,
        "serverPort", serverPort,
        "serviceName", "product-service",
        "startupTime", System.currentTimeMillis() - (System.currentTimeMillis() % 1000000),
        "currentTime", System.currentTimeMillis()
    );
  }

  /**
   * 健康检查端点
   * GET /api/products/health
   */
  @GetMapping("/health")
  public Map<String, Object> health() {
    return Map.of(
        "status", "UP",
        "service", "product-service",
        "timestamp", System.currentTimeMillis(),
        "totalProducts", products.size()
    );
  }

  /**
   * 模拟处理时间
   * 不同实例有不同的处理时间，便于观察负载均衡效果
   */
  private void simulateProcessingTime() {
    try {
      // 基于端口号模拟不同的处理时间
      int port = Integer.parseInt(serverPort);
      int delay = port == 8082 ? 50 : 30; // 8082端口延迟50ms，8084端口延迟30ms
      Thread.sleep(delay);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}
